# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(ropls)
library(magrittr)
library(scales)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

samples <- sampleInfo$SampleID
samples

classNotes <- unique(sampleInfo$ClassNote)

allData <- read_tsv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  select(c("Metabolite", samples)) %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    for (group in classNotes) {
      sampleIds <- sampleInfo %>%
        filter(ClassNote == group) %>%
        .$SampleID
      groupData <- result[sampleIds] %>%
        unlist()
      mean <- mean(groupData)
      result[, paste0(group, ".Mean")] <- mean
      result[, paste0(group, ".SD")] = sd(groupData)
      median <- median(groupData)
      result[, paste0(group, ".Median")] <- median
      iqr11 <- quantile(groupData, 0.25)
      iqr12 <- quantile(groupData, 0.75)
      iqr1 <- paste0("[", iqr11, ",", iqr12, "]")
      result[, paste0(group, ".IQR")] <- iqr1
      result[, paste0(group, ".Min")] <- min(groupData)
      result[, paste0(group, ".Max")] <- max(groupData)
    }
    result
  }) %>%
  select(-c(samples))

head(allData)

parent <- "./"
fileName <- paste0(parent, "Basic_Statistics.csv")
data <- allData
write.csv(data, fileName, row.names = F)


